<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Text;
//use App\User;
use DB;

class WxxController extends Controller
{

    public $app = null;
    public function __construct(){
      $options = [
        'debug'  => true,
        'app_id' => 'wxb07775315e81c55f',
        'secret' => 'dfb1fbcec72fd7a9a1b5ebf5e9a135a9',
        'token'  => 'johntest',
        // 'aes_key' => null, // 可选
        'log' => [
            'level' => 'debug',
            'file'  => '/tmp/easywechat.log', // XXX: 绝对路径！！！！
        ],


        'guzzle'=>[
          'timeout'=>5.0,
          'verify'=>false,
        ]
        //...
      ];
      $this->app = new Application($options);
    }
    //
    public function index(){
      $server = $this->app->server;
//       $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
//        $server->setMessageHandler(function($message){
//
//
//       //     // 注意，这里的 $message 不仅仅是用户发来的消息，也可能是事件
//       //     // 当 $message->MsgType 为 event 时为事件
//           if ($message->MsgType == 'event') {
//               if($message->Event == 'subscribe') {
//                   return $this->guanzhu($message);
//               }elseif ($message->Event == 'unsubscribe') {
//                   $this->quxiao($message);
//               }elseif($message->Event == 'CLICK'){
// /******************************************************************/
//                 return $message->FromUserName;  //openid
//                 $content = $message->EventKey;
//                 // $text = new Text(['content' => $content]);
//                 // return $text;
//                 if( $content == 'V1001_TODAY_MUSIC' ){
//                   $notice = $this->app->notice;
//                   //return $this->sendtpl_msg();
//                   // return '123';
//                   $opid='oWG5OxB2GWkZHo5EgdEKbIsbzY6s';
//
//                   $sj=date("Y/m/d H:i");
//                   $tempid="9wbd29srqzLJlHafdhq0iF-GzZ8CFi-lm8Ms3Ih3euM";
//                   // $tempid="qGpA2yoFIKI-VB2RAiiLpHGXxSkTBdqjGRs9HVMU58w";
//                   $template=array(
//                     'touser'=>$opid,
//                     'template_id'=>$tempid,
//                             'url'=>"http://baidu.com",
//                       'topcolor'=>"#FF0000",
//                     'data'=>array(
//                           'first'=>array('value'=>urlencode("内测：Hommer 系统"),'color'=>"#008800"),
//                           // 'keyword1'=>array('value'=>urlencode("您有新的消息！"),'color'=>'#000000'),
//                           // 'keyword2'=>array('value'=>urlencode($sj),'color'=>'#000000'),
//                           // 'keyword3'=>array('value'=>urlencode('哈哈哈不能'),'color'=>'#FF0000'),
//                           // 'remark'=>array('value'=>urlencode("菜单查询详情"),'color'=>'#008800')
//                           )
//                   );
//                   $data=urldecode(json_encode($template));
//                   $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=VPGOUicIiy1sUHWOmulRP_zlN0-VlcbgP4VRtUkxcQe_P5pE7l430akfwD-dBEpmP_4hQYzowMaqT81-kPgAgRa3UStPrPicncjlg0zLdLvCjBm8F762J9yH78kjYfk5QBEjABAGRU";
//                     $curl = curl_init();
//                     curl_setopt($curl, CURLOPT_URL, $url);
//                     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
//                     curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
//                     if (!empty($data)){
//                         curl_setopt($curl, CURLOPT_POST, 1);
//                         curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//                     }
//                     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//                     return $output = curl_exec($curl);
//                     curl_close($curl);
//
// /*************************************/
//
//
//
//
//                   // $text = new Text(['content' => '没有歌曲']);
//                   // return $text;
//
//               }
// /****************************CLICK事件结束 *********************************/
//
//
//           }elseif($message->Event == 'LOCATION'){
//                 //return "您的地理位置维度\n".$message->Latitude."\n您的地理位置精度\n".$message->Longitude;
//                 return DB::table('cats')->insert(['name'=>'张三','age'=>23])?1:0;
//           }
//           }
//
//
//
//    });

  //  if(!empty($postStr)){
  //    $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  //    $fromUsername = $postObj->FromUserName;
  //    $toUsername = $postObj->ToUserName;
  //    $keyword = trim($postObj->Content);
  //    $msgType = $postObj->MsgType;
  //    $time = time();
  //    $textTpl = "<xml>
  //        <ToUserName><![CDATA[%s]]></ToUserName>
  //        <FromUserName><![CDATA[%s]]></FromUserName>
  //        <CreateTime>%s</CreateTime>
  //        <MsgType><![CDATA[%s]]></MsgType>
  //        <Content><![CDATA[%s]]></Content>
  //        <FuncFlag>0</FuncFlag>
  //        </xml>";
  //        if($msgType == 'location'){
   //
  //            $msgType = "text";
  //            $jss = file_get_contents("http://api.map.baidu.com/telematics/v3/local?location=$postObj->Location_Y,$postObj->Location_X&keyWord=厕所&output=json&ak=GvvubztArvpOKQ1D1qqRYiGb0sBGZfGw");
  //            $a = json_decode($jss,true)['pointList'];
  //            $ctro = '您的维度'.$postObj->Location_Y.'您的精度'.$postObj->Location_X;
  //            //$ctro = '您的维度';
  //            $contentStr = null;
  //            foreach ($a as $v) {
  //                $contentStr .= "在$v[address]有茅坑 , 距离您$v[distance]米\n";
  //            }
  //            //$contentStr = "您的维度是: ".$postObj->Location_X.'您的精度是: '.$postObj->Location_Y;
  //            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $ctro);
  //            echo $resultStr;
   //
  //        }
   //
  //  }







      $response = $this->app->server->serve();
      // 将响应输出$response->send(); // Laravel 里请使用：
      return $response;
      }






    // public function index()
    // {
    //
    //
    //             $muTpl = "<xml>
    //                         <ToUserName><![CDATA[%s]]></ToUserName>
    //                         <FromUserName><![CDATA[%s]]></FromUserName>
    //                         <CreateTime>%s</CreateTime>
    //                         <MsgType><![CDATA[music]]></MsgType>
    //                         <Music>
    //                         <Title><![CDATA[%s]]></Title>
    //                         <Description><![CDATA[%s]]></Description>
    //                         <MusicUrl><![CDATA[%s]]></MusicUrl>
    //                         <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
    //
    //                         </Music>
    //                     </xml>";
    //             $newTpl = "<xml>
    //                             <ToUserName><![CDATA[%s]]></ToUserName>
    //                             <FromUserName><![CDATA[%s]]></FromUserName>
    //                             <CreateTime>%s</CreateTime>
    //                             <MsgType><![CDATA[news]]></MsgType>
    //                             <ArticleCount>1</ArticleCount>
    //                             <Articles>
    //                             <item>
    //                             <Title><![CDATA[%s]]></Title>
    //                             <Description><![CDATA[%s]]></Description>
    //                             <PicUrl><![CDATA[%s]]></PicUrl>
    //                             <Url><![CDATA[%s]]></Url>
    //                             </item>
    //                             </Articles>
    //                         </xml>";
    //
    //             if($msgType == 'event'){
    //                 if($postObj->Event == 'subscribe'){
    //                 $msgType = "text";
    //                 $contentStr = "吉吉 , 欢迎你";
    //                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    //                 echo $resultStr;
    //
    //                 }
    //             }else if ($msgType == 'image'){
    //
    //                 $msgType = "text";
    //                 $jss = file_get_contents("http://apicn.faceplusplus.com/v2/detection/detect?api_key=8ab79f397dc2666fa86eec936e27d964&api_secret=xwWoI7a6HkMpP-U6N1p1jtMdInFN0gxB&url=$postObj->PicUrl&attribute=glass,pose,gender,age,race,smiling");
    //                 $a = count( json_decode($jss,true)['face']);
    //                 $contentStr = "这个图片有".$a."个人";
    //                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    //                 echo $resultStr;
    //             }else if ($msgType == 'voice'){
    //                 $msgType = "text";
    //                 $contentStr = $postObj->Recognition;
    //                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    //                 echo $resultStr;
    //             }elseelseif($msgType == 'text'){
    //                 if($keyword == 'beyond'){
    //                     $title = '音乐';
    //                     $desc = '世间纵有千万曲，人间再无黄家驹';
    //                     $murl = 'http://wxx.ittun.com/beyond.mp3';
    //                     $resultStr = sprintf($muTpl, $fromUsername, $toUsername, $time, $title, $desc , $murl ,$murl);
    //                     echo $resultStr;
    //                 }elseif($keyword == 'cang'){
    //                     $title = '图片';
    //                     $desc = '苍老湿';
    //                     $murl = 'http://wxx.ittun.com/cang.jpg';
    //                     $url = 'http://baidu.com';
    //                     $resultStr = sprintf($newTpl, $fromUsername, $toUsername, $time, $title, $desc , $murl ,$url);
    //                     echo $resultStr;
    //                 }
    //                 $msgType = "text";
    //                 if($keyword == '好'){
    //                     $contentStr = "不好 , 好什么好";
    //                 }else{
    //                     $contentStr = "别随便乱发";
    //                 }
    //                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    //                 echo $resultStr;
    //
    //
    //             } else if(!empty( $keyword )){
    //
    //             }else{
    //               echo "Input something...";
    //             }
    //
    //
    //     }else {
    //       echo "";
    //       exit;
    //         }
    // }

      public function guanzhu($message){

        $openId = $message->FromUserName;

        $user = User::where('openid',$openId)->first();

        ////1:之前关注过，现在没有，修改state =1;
        if($user && $user->state == 0){
            $user->state = 1;
            $user->save();
        }else{
          //2:二维码不带参数，作为一级代理
            $userModel = new User();
            $userModel->openid = $openId;

            $userService = $this->app->user;
            $user = $userService->get($openId);
            $userModel->name = $user->nickname;

            $userModel->subtime = time();

              //3:二维码有参数，获取二维码参数，惊醒级别处理
            if($message->EventKey){
                $puid = str_replace('qrscene_','',$message->EventKey);
                $puser = DB::table('users')->where('uid',$puid)->first();
                $userModel->p1 = $puid;
                $userModel->p2 = $puser->p1;
                $userModel->p3 = $puser->p2;
            }
            $userModel->save();
            $this->qrcode($userModel->uid);
        }

        // $userModel->save();

        $text = new Text(['content' => '西岭老湿恨你']);
        return $text;
      }

      public function qrcode($uid){
          $qrcode = $this->app->qrcode;
          $result = $qrcode->forever($uid);
          $ticket = $result->ticket;
          $url = $qrcode->url($ticket);
          $content = file_get_contents($url); // 得到二进制图片内容
          $path = $this->mkd().'qr_'.$uid.'.jpg';
          file_put_contents(public_path().$path, $content); // 写入文件
      }
      protected function mkd(){
          $today = date('/Y/m/');
          if(!is_dir(public_path().$today)){
              mkdir(public_path().$today,0777,true);
          }

          return $today;
      }

      public function quxiao($message){
          $info = User::where('openid',$message->FromUserName)->first();
          if($info){
              $info->state = 0;
              $info->save();
          }
      }

}
